import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 薪资管理系统核心类，处理员工数据管理、登录、薪资查询等核心逻辑
 */
class SalaryManagementSystem {
    private List<Employee> employees = new ArrayList<>(); // 员工列表
    private final String STORAGE_FILE = "employees.ser"; // 数据存储文件
    private Map<String, Employee> usernameMap = new HashMap<>(); // 账号-员工映射表（快速登录验证）

    // 从文件加载员工数据
    public void loadEmployees() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(STORAGE_FILE))) {
            employees = (List<Employee>) ois.readObject();
            // 重建账号映射表
            usernameMap.clear();
            for (Employee emp : employees) {
                usernameMap.put(emp.getUsername(), emp);
            }
            System.out.println("员工数据已加载，共" + employees.size() + "名员工");
        } catch (FileNotFoundException e) {
            System.out.println("未找到存储文件，将创建新的员工列表");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据失败：" + e.getMessage());
        }
    }

    // 保存员工数据到文件
    public void saveEmployees() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(STORAGE_FILE))) {
            oos.writeObject(employees);
            // 更新账号映射表
            usernameMap.clear();
            for (Employee emp : employees) {
                usernameMap.put(emp.getUsername(), emp);
            }
            System.out.println("员工数据已保存");
        } catch (IOException e) {
            System.out.println("保存数据失败：" + e.getMessage());
        }
    }

    // 添加新员工
    public void addEmployee(Employee employee) {
        employees.add(employee);
        usernameMap.put(employee.getUsername(), employee);
    }

    // 登录验证
    public Employee login(String username, String password) throws LoginFailedException {
        Employee emp = usernameMap.get(username);
        if (emp == null) {
            throw new LoginFailedException("账号不存在");
        }
        if (!emp.getPassword().equals(password)) {
            throw new LoginFailedException("密码错误");
        }
        return emp;
    }

    // 获取个人工资条
    public String getPersonalPaySlip(Employee employee) {
        return employee.generatePaySlip();
    }

    // 验证原密码是否正确
    public boolean verifyOldPassword(Employee employee, String oldPassword) {
        return employee.getPassword().equals(oldPassword);
    }

    // 修改密码（需验证原密码）
    public void changePassword(Employee employee, String oldPassword, String newPassword) throws Exception {
        if (!verifyOldPassword(employee, oldPassword)) {
            throw new Exception("原密码错误，修改失败");
        }
        if (newPassword.isEmpty()) {
            throw new Exception("新密码不能为空");
        }
        employee.setPassword(newPassword);
        saveEmployees(); // 立即保存
    }

    // 修改账号（需确保新账号唯一）
    public void changeUsername(Employee employee, String newUsername) throws Exception {
        if (newUsername.isEmpty()) {
            throw new Exception("新账号不能为空");
        }
        if (usernameMap.containsKey(newUsername)) {
            throw new Exception("新账号已存在，请更换");
        }
        // 更新映射表和员工账号
        usernameMap.remove(employee.getUsername());
        employee.setUsername(newUsername);
        usernameMap.put(newUsername, employee);
        saveEmployees(); // 立即保存
    }

    // 判断员工列表是否为空（用于首次初始化）
    public boolean isEmployeesEmpty() {
        return employees.isEmpty();
    }
}